<template>
    <view class="order">
        <swiper
            class="swiper" 
            circular
            indicator-dots
            autoplay
        >
            <swiper-item
                v-for="(item, index) in formData?.galleryImages"
                :key="'0-' + index"
            >
                <image 
                    :src="CONSTANT_URL.TY+item.imageUrl" 
                    :draggable="false"
                    mode="scaleToFill"
                    class="swiper-img"
                ></image>
            </swiper-item>
        </swiper>
        <view class="msg1-box">
            <view class="msg1">
                <view class="msg1-price">
                    <!-- <view class="msg1-price-text-1">
                        积分兑换
                    </view> -->
                    <view class="msg1-price-text-2">
                        ￥{{ formData?.skus?.[0].price ? Number(formData?.skus?.[0].price).toFixed(2) : 0 }}
                    </view>
                </view>
                <view class="msg1-num">
                    <!-- 已售{{  }}件 -->
                </view>
            </view>
            <view class="title">
                {{ formData?.name }}
            </view>
        </view>
        <view class="msg2-box">
            <!-- <view 
                v-if="formData.zsgm_ex12"
                class="msg2-content-1"
            >
                <view class="msg2-content-1-color">产地信息：</view>
                <view>{{ formData.zsgm_ex12 }}</view>
            </view> -->
            <view class="msg2-content-1">
                <view class="msg2-content-1-color">运费金额：</view>
                <view>商家包邮费</view>
            </view>
            <view 
                class="msg2-content-1"
                @click="callPhone"
            >
                <view class="msg2-content-1-color">客服电话：</view>
                <view>13162676119</view>
                <view class="iconfont icon-kefuzhongxin msg2-content-1-icon"></view>
            </view>
            <view class="msg2-content-1">
                <view class="msg2-content-1-color">客服时间：</view>
                <view>周一至周日09:00-22:00</view>
            </view>
            <view class="msg2-content-1">
                <view class="msg2-content-1-color">发货时间：</view>
                <view>预计1-7天内发货</view>
            </view>
        </view>
        <!-- <view class="specifications">
            {{ formData.zsgm_ex10 }}
        </view> -->
        <view class="desc">
            {{ formData?.description }}
        </view>
        <view class="text-1-box">
            商品详情
        </view>
        <image
            v-for="(item, index) in formData?.detailImages"
            :key="'1-' + index"
            :src="CONSTANT_URL.TY+item.imageUrl"
            :draggable="false"
            mode="widthFix"
            style="width: 100vw;"
        />
        <view class="goods-carts">
            <uni-goods-nav
                :fill="true"  
                :options="options" 
                :buttonGroup="buttonGroup"  
                style="position: fixed; left: 0; right: 0; bottom: 0;"
                @click="onClick" 
                @buttonClick="buttonClick" 
            />
        </view>    
        
        <vk-data-goods-sku-popup
            ref="skuPopup"
            v-model="skuKey"
            border-radius="20"
            :z-index="990"
            :localdata="goodsInfo"
            :mode="skuMode"
            :amount-type="0"
            :step-strictly="true"
            theme="red-black"
            @open="onOpenSkuPopup"
            @close="onCloseSkuPopup"
            @add-cart="addCart"
            @buy-now="buyNow"
        ></vk-data-goods-sku-popup>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload, onPullDownRefresh, onReachBottom, onShareTimeline, onShareAppMessage } from '@dcloudio/uni-app'
    import { markRaw, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { getProductsIdApi,getCartApi,PostCartApi } from '@/apis'
    import { CONSTANT_URL } from '@/apis/constant.ts'
    const formData: Ref<any> = ref({
        commodityNum: 1,
        
        // name: '12瓶装易捷水', //商品名称
        // price: 120, //售价积分
        // xsl: 62, //销售量
        // zsgm_id: 100,
        // images: 'http://oss3.smartyoke.com/putaway/23e338cee2cb4428b7a29f45e4ff0268.jpg', //商品图片
        // zsgm_ex3: 0, //库存数量
        // description: '商品简介', //商品简介
        // zsgm_ex7: '商品类型名称', //商品类型名称
        // zsgm_ex8: '已上架', //是否上架:未上架 ,已上架
        // zsgm_ex9: '未审核', //审核状态:未审核 ,已审核
        // zsgm_create_time: '', //创建时间
        // zsgm_dj_ex3: 0, //冻结数量
        
    })
    const options: Ref<any[]> = ref([
  //       {
		// 	icon: 'headphones',
		// 	text: '客服'
		// }, {
		// 	icon: 'shop',
		// 	text: '店铺',
		// 	info: 2, //右上角数字角标
		// 	infoBackgroundColor:'#007aff', //角标背景色
		// 	infoColor:"red" //角标前景色
		// }, 
        {
			icon: 'cart',
			text: '购物车',
			info: 0
		}
    ])
    const buttonGroup: Ref<any[]> = ref([
        {
          text: '加入购物车',
          backgroundColor: 'linear-gradient(90deg, #ff4b5a, #c83b45)',
          color: '#fff'
        },
        {
          text: '立即购买',
          // backgroundColor: '#46c1ff',
          backgroundColor: 'linear-gradient(90deg, #ff4b5a, #c83b45)',
          color: '#fff'
        }
    ])
    
    onLoad((val: any) => {
        console.log(val)
        // if (!uni.getStorageSync('token')) {
        //     let pages = getCurrentPages()
        //     let url = pages[pages.length - 1].route
        //     uni.reLaunch({
        //         url: "/pages/login/login?url=/" + url
        //     })
        // }
       getProductsIdApi(val.id).then((res: any)=> {
           formData.value = res.data
           let sku_list: any[] = []
           let spec_list: any[] = [
               {
                   name: '规格',
                   list: []
               }
           ]
           res.data.skus.forEach((item: any, index: number) => {
               sku_list.push({
                   "_id": item.id,
                   "goods_id": res.data.id,
                   "goods_name": res.data.name,
                   "image": CONSTANT_URL.TY+item.coverImageUrl,
                   "price": item.price,
                   "sku_name_arr": [item.skuName],
                   "stock": item.stock
               })
               spec_list[0].list.push({
                   "name": item.skuName,
               })
           })
           
           goodsInfo.value = {
              _id: res.data.skus[0].id,
              name: res.data.name,
              goods_thumb: CONSTANT_URL.TY+res.data.skus?.[0]?.coverImageUrl,  
              sku_list: sku_list,
              spec_list: spec_list,
          }
          
          getCartApi({
              userId : uni.getStorageSync('userId')
          }).then((res2: any)=> {
              // 购物车数量
              options.value[0].info = res2.data.length
          })
           // goodsInfo.value = {
           //     _id: res.data.goodMain[0].zsgm_id,
           //     name: res.data.goodMain[0].zsgm_ex1,
           //     goods_thumb: res.data.goodMain[0].images?.split(',')[0],
           //     sku_list: [],
           //     spec_list: [],
           // }
           // res.data.skuList.forEach((item1: any, index1: number) => {
           //     if (item1.zsg_ex8 == '已上架') {
           //         goodsInfo.value.sku_list.push({
           //             _id: item1.zsg_id,
           //             goods_id: item1.zsg_main_id,
           //             goods_name: item1.zsg_ex1,
           //             image: item1.zsg_ex6?.split(',')[0],
           //             price: Number(item1.zsg_ex2),
           //             sku_name_arr: item1.spec_values.split(','),
           //             xsl: Number(item1.zsg_ex3)
           //         })
           //     }
               
           // })
           // res.data.specList.forEach((item2: any, index2: number) => {
           //     goodsInfo.value.spec_list.push({
           //         name: item2.zsas_ex1,
           //         list: [],
           //     })
           //     item2.spec_values.split(',').forEach((item3: any, index3: number) => {
           //         goodsInfo.value.spec_list[index2].list.push({
           //             name: item3
           //         })
           //     })
           // })
           // console.log(goodsInfo.value)
           
           
           
           
           
           // goodsInfo.value = {
           //     "_id": "001",
           //     "name": "iphone11",
           //     "goods_thumb": "https://img14.360buyimg.com/n0/jfs/t1/59022/28/10293/141808/5d78088fEf6e7862d/68836f52ffaaad96.jpg",
           //     "sku_list": [
           //         {
           //             "_id": "001",
           //             "goods_id": "001",
           //             "goods_name": "iphone11",
           //             "image": "https://img14.360buyimg.com/n0/jfs/t1/79668/22/9987/159271/5d780915Ebf9bf3f4/6a1b2703a9ed8737.jpg",
           //             "price": 19800,
           //             "sku_name_arr": ["红色", "128G", "公开版"],
           //             "stock": 1000
           //         },
           //         {
           //             "_id": "002",
           //             "goods_id": "001",
           //             "goods_name": "iphone11",
           //             "image": "https://img14.360buyimg.com/n0/jfs/t1/52252/35/10516/124064/5d7808e0E46202391/7100f3733a1c1f00.jpg",
           //             "price": 9800,
           //             "sku_name_arr": ["白色", "256G", "公开版"],
           //             "stock": 100
           //         },
           //         {
           //             "_id": "003",
           //             "goods_id": "001",
           //             "goods_name": "iphone11",
           //             "image": "https://img14.360buyimg.com/n0/jfs/t1/79668/22/9987/159271/5d780915Ebf9bf3f4/6a1b2703a9ed8737.jpg",
           //             "price": 19800,
           //             "sku_name_arr": ["红色", "256G", "公开版"],
           //             "stock": 1
           //         }
           //     ],
           //     "spec_list": [
           //         {
           //             "name": "颜色",
           //             "list": [
           //                 { "name": "红色" },
           //                 { "name": "黑色" },
           //                 { "name": "白色" }
           //             ]
           //         },
           //         {
           //             "name": "内存",
           //             "list": [
           //                 { "name": "128G" },
           //                 { "name": "256G" }
           //             ],
           //         },
           //         {
           //             "name": "版本",
           //             "list": [
           //                 { "name": "公开版" },
           //                 { "name": "非公开版" }
           //             ]
           //         }
           //     ]
           // }
           
       })
       
    })
    onShow(() => {
        
    })
    const onClick = (e) => {
        uni.switchTab({
            url: '/pages/shoppingCart/shoppingCart'
        })
    }
    const buttonClick = (e) => {
        console.log(e)
        if (e.content.text == '加入购物车') {
            // popup2.value.open()
            skuMode.value = 2
            skuKey.value = true
        } else if (e.content.text == '立即购买') {
            skuMode.value = 3
            skuKey.value = true
        }
    }
   
    const callPhone = () => {
        uni.makePhoneCall({
        	phoneNumber: '057187551689',
            success: () => {
                console.log('成功')
            },
            fail: () => {
                console.log('失败')
            },
            complete: () => {
                console.log('一定走')
            }
        })
    }
    
    const skuKey: Ref<boolean> = ref(false) // 是否打开SKU弹窗
    const skuMode: Ref<number> = ref(3) // SKU弹窗模式 1:都显示 2:只显示购物车 3:只显示立即购买
    const goodsInfo: Ref<any> = ref({}) // 后端返回的商品信息
    // sku组件 开始-----------------------------------------------------------
    const onOpenSkuPopup = () => {
        console.log("监听 - 打开sku组件");
    }
    const onCloseSkuPopup = () => {
        console.log("监听 - 关闭sku组件");
    }
    // 加入购物车前的判断
    const addCartFn = (obj: any) => {
        let { selectShop } = obj;
        // 模拟添加到购物车,请替换成你自己的添加到购物车逻辑
        let res: any = {};
        let name = selectShop.goods_name;
        console.log(selectShop)
        if (selectShop.sku_name != "默认") {
            name += "-" + selectShop.sku_name_arr;
        }
        res.msg = `${name} 已添加到购物车`;
        if (typeof obj.success == "function") obj.success(res);
    }
    // 加入购物车按钮
    const addCart = (selectShop: any) => {
        console.log("监听 - 加入购物车");
        addCartFn({
            selectShop: selectShop,
            success: async(res: any) => {
                // 实际业务时,请替换自己的加入购物车逻辑
                // options.value[0].info += selectShop.buy_num
                console.log(selectShop)
                console.log(11111)
                
                await PostCartApi({
                    productSkuId: selectShop._id,
                    userId: uni.getStorageSync('userId'),
                    quantity: selectShop.buy_num,
                })
                getCartApi({
                    userId : uni.getStorageSync('userId')
                }).then((res: any)=> {
                    // 购物车数量
                    options.value[0].info = res.data.length
                })
                uni.showToast({
                    title: res.msg,
                    icon: "none"
                });
                setTimeout(() => {
                    skuKey.value = false;
                }, 300);
            }
        });
    }
    // 立即购买
    const buyNow = (selectShop: any) => {
        console.log("监听 - 立即购买");
        addCartFn({
            selectShop: selectShop,
            success: res => {
                // 实际业务时,请替换自己的立即购买逻辑
                uni.showToast({
                    title: '立即购买',
                    icon: "none"
                });
                uni.setStorageSync('commoditiesClearingArr', JSON.stringify([formData.value]))
                uni.navigateTo({
                    url: '/pages/commoditiesClearing/commoditiesClearing'
                })
            }
        });
    }
    // const setfVal = (selectShop: any) => {
    //     formData.value = {...formData.value, ...{
    //         commodityNum: selectShop.buy_num,
    //         zsg_main_id: selectShop.goods_id,
    //         zsg_ex1: selectShop.goods_name,
    //         zsg_ex6: selectShop.image?.split(',')[0],
    //         zsg_ex2: selectShop.price,
    //         spec_values: selectShop.sku_name_arr.join(','),
    //         zsg_ex3: selectShop.xsl,
    //         zsg_id: selectShop._id,
    //     }}
    // }
</script>

<style lang="scss" scoped>
    .order {
        min-height: 100vh;
        background-color: #f2f2f2;
    }
    .swiper {
        height: 680rpx;
        box-sizing: border-box;
        // padding: 10rpx;
        // border-radius: 20rpx;
    }
    .swiper-img {
        width: 100%;
        height: 100%
    }
    .msg1-box {
        background: #fff;
        padding: 30rpx 20rpx;
        .msg1 {
            // height: 100rpx;
            // background: linear-gradient(to bottom, #46c1ff, #e2e2e2);
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-sizing: border-box;
            // padding: 0 10rpx;
            .msg1-price {
                display: flex;
                align-items: center;
                .msg1-price-text-1 {
                    height: 45rpx;
                    background: #f2403c;
                    box-sizing: border-box;
                    padding: 5rpx;
                    border-radius: 10rpx;
                    font-size: 24rpx;
                    color: #fff;
                }
                .msg1-price-text-2 {
                   font-size: 38rpx;
                   // font-weight: bold;
                   color: red;
                   // padding-left: 10rpx;
                }
            }
            .msg1-num {
                font-size: 30rpx;
                // color: #fff;
                color: #c0c1c3;
            }
        }
        .title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            box-sizing: border-box;
            // padding: 10rpx;
            letter-spacing: 1rpx;
            padding-top: 20rpx;
        }
    }
    .msg2-box {
        margin-top: 20rpx;
        box-sizing: border-box;
        padding: 20rpx 20rpx;
        // border-radius: 20rpx;
        background: #fff;
        font-size: 28rpx;
        .msg2-content-1 {
            display: flex;
            padding: 10rpx 0;
            .msg2-content-1-color {
                color: #909094;
            }
            .msg2-content-1-icon {
                margin-left: 10rpx;
                color: #023e9e;
                font-size: 36rpx;
            }
        }
    }
    .specifications {
        font-size: 30rpx;
        font-weight: bold;
        box-sizing: border-box;
        padding: 10rpx;
        letter-spacing: 1rpx;
    }
    .desc {
        margin-top: 20rpx;
        box-sizing: border-box;
        // border-radius: 20rpx;
        padding: 20rpx;
        line-height: 50rpx;
        background: #fff;
        font-size: 28rpx;
        text-indent: 56rpx;
        letter-spacing: 1rpx;
        color: #505050;
    }
    .text-1-box {
        text-align: center;
        padding: 20rpx 0;
        color: #6f6f6f;
    }
    .goods-carts {
        height: 110rpx;
        :deep(.uni-tab__cart-box) {
            height: 110rpx;
        }
    }
    .my-popup1-box {
        // background: #f2f2f2;
        background: #fff;
        // width: 600rpx; 
        box-sizing: border-box; 
        font-size: 28rpx;
        // padding: 0 0 30rpx 0; 
        // border-radius: 50rpx 50rpx 0rpx 0rpx;
        .my-popup1-header {
            display: flex;
            // justify-content: space-between;
            align-items: center;
            height: 100rpx;
            background: #fff;
            .my-popup1-header-main {
                flex: 1;
                padding: 0 10rpx;
                font-size: 26rpx
            }
            .my-popup1-header-icon-img {
                width: 50rpx;
                height: 50rpx
            }
            
        }
        
        .my-popup1-main-1 {
            // background: #fff;
            display: flex;
            // margin-top: 20rpx;
            box-sizing: border-box;
            padding: 20rpx 20rpx;
            .my-popup1-main-1-img {
                width: 180rpx;
                height: 180rpx;
                box-sizing: border-box;
                border-radius: 10rpx;
            }
            .my-popup1-main-1-text {
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                box-sizing: border-box;
                padding-left: 10rpx;
                .my-popup1-main-1-text-1 {
                    height: 80rpx;
                    overflow: hidden;
                }
                .my-popup1-main-1-text-3 {
                    display: flex;
                    justify-content: space-between;
                    .my-popup1-main-1-text-3-right {
                       // text-align: right;
                       color: #f2403c;
                       // font-weight: bold;
                       // padding-left: 10rpx;
                    }
                }
            }
        }
        .my-popup1-main-2 {
            box-sizing: border-box;
            padding: 20rpx 20rpx;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            // font-size: 28rpx;
            .my-popup1-main-2-title-1 {
                padding-bottom: 20rpx;
            }
            .my-popup1-main-2-text-1 {
                display: flex;
                .my-popup1-main-2-text-2 {
                    box-sizing: border-box;
                    text-align: center;
                    padding: 10rpx;
                    margin: 10rpx;
                    background: #dae4f2;
                }
            }
        }
        .my-popup1-button {
            background-color: #fff;
            height: 110rpx;
            .my-popup1-button-disabled-btn {
                background-color: rgba(41, 121, 255, 0.6) !important;
                color: #fff9f9 !important;
            }
            .my-popup1-button-default-btn {
                background-color: #2979ff !important;
                color: #fff !important;
                font-size: 28rpx;
                padding: 15rpx 0;
            }
        }
    }
    
</style>
